<template>
  <div class="fill">
    <el-form ref="form" :model="transform2FormObj.formData" :rules="transform2FormObj.rules" label-width="100px"
             label-suffix="：">
      <template v-for="(formItem, index) of transform2FormObj.formItems">
        <el-form-item ref="form"
            :label="formItem.label || '未设置label'"
            :label-width="formItem.labelWidth || null"
            :prop="formItem.field">
          <component
              :is="formItem.type"
              v-bind="formItem"
              :ref="formItem.field"
              :formData="formData"
              @input="setValue(formItem.field, $event)"
              :value="formData[formItem.field]"
          />
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
const cloneDeep = require('clone')

const elMap = {
  "input": {is: "el-input", type: "input"},
  "textarea": {is: "el-input", type: "textarea"},
}
export default {
  name: "t-form",
  props: {
    // 表单描述
    formDesc: {
      type: Object,
      required: true
    },
    // 表单数据
    formData: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      elMap,
      oldFormData: {}
    }
  },
  computed: {
    transform2FormObj() {
      let formItems = []
      let rules = {}

      let formObj = {
        formItems,
        rules,
        formData: this.formData
      }


      Object.keys(this.formDesc).forEach(key => {
        //rules
        if (this.formDesc[key].rules)
          rules[key] = this.formDesc[key].rules
        //formItems
        formItems.push(this.transformFormItem(this.formDesc[key], key))
      })
      return formObj
    }
  },
  methods: {
    transformFormItem(formDesc, key) {
      let res = {...formDesc, field: key}
      res = {...res, ...this.elMap[res.type]}
      delete res.rules
      return res
    },


    handleChange(field, val) {
      this.oldFormData = cloneDeep(this.formData)
      this.$set(this.formData, field, val)
      this.$emit('input', this.formData)
    },
    setValue(field, val) {
      this.handleChange(field, val)
    },
  }
}
</script>

<style lang="less" scoped>

</style>